package com.hnas.common.interceptors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.hnas.sys.service.system.dto.DTOUser;

public class LoginInterceptor implements HandlerInterceptor{

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String url = request.getRequestURI();  
        //URL:login.jsp是公开的;这个demo是除了login.jsp是可以公开访问的，其它的URL都进行拦截控制  
		if(url.indexOf("officialChannel")>=0){  
			 String redirectPath =  request.getContextPath()+"/official_channel.jsp";
		     response.sendRedirect(redirectPath);
	         return false;  
	    } 
		
        if(url.indexOf("login")>=0){  
            return true;  
        }  
        //获取Session  
        HttpSession session = request.getSession();  
        DTOUser user = (DTOUser)session.getAttribute("currentUser");  
          
        if(user != null && StringUtils.isNotEmpty(user.getUsername())){  
            return true;  
        }  
        //不符合条件的，跳转到登录界面  
        String redirectPath =  request.getContextPath()+"/login.jsp";
        response.sendRedirect(redirectPath);
          
        return false;  
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		
	}
}
